package abcy.cloud.bloggateway.filter;

import abcy.cloud.bloggateway.exception.NoPermisisonsException;
import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;
    // 白名单



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> param = new HashMap<>();
        String urlStr1 = "http://localhost:" + 8083 + "/syswhite/selectWhiteList";

        HttpEntity<Map<String, Object>> entity1 = new HttpEntity<>(param, headers);
        Map<?, ?> result = restTemplate.exchange(urlStr1, HttpMethod.POST,
                entity1, Map.class).getBody();
        List<String> whiteList = (List<String>) result.get("whiteList");

        String url = exchange.getRequest().getURI().getPath();
        log.info("url:{}", url);
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isEmpty(token) && whiteList.contains(url)) {
            return chain.filter(exchange);
        } else if (StringUtils.isNotEmpty(token)){
            Map<String, Object> map1 = new HashMap<>();
            map1 = (Map<String, Object>) redisTemplate.opsForValue().get("userInfo");
            if (map1 != null) {
                List<String> permissions = (List<String>) map1.get("permissions");
                if (permissions.contains(url)) {
                    return chain.filter(exchange);
                } else {
                    throw new NoPermisisonsException(403, url, "无权限");
                }
            } else {
                return Mono.error(new RuntimeException());
            }
        } else {
            return Mono.error(new RuntimeException());
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
